package com.easylinkin.linkappapi.interceptor;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.space.entity.LinkappSpace;

@Component
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
    RowBounds.class, ResultHandler.class}))
public class MybatisInterceptor implements Interceptor {

    private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(MybatisInterceptor.class);

    @Resource
    LinkappUserContextProducer linkappUserContextProducer;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs(); //方法参数
        MappedStatement mappedStatement = (MappedStatement) args[0];
        String sqlKey = mappedStatement.getId();
        // 获取sql
        String sql = getSqlByInvocation(invocation);
        if (StringUtils.isBlank(sql)) {
            return invocation.proceed();
        }
        // 全局查询放弃拦截
        if (sqlKey.endsWith("Global")) {
            return invocation.proceed();
        }

        for (String tableName : invcationTables()) {
            if (sql.indexOf(tableName) != -1) {
                LinkappUser linkappUser = linkappUserContextProducer.getCurrent();
                if (linkappUser != null) {
//					LOGGER.info("before:" + sql);
                    for (String id : sqlId()) {
                        if (sqlKey.endsWith(id)) {
                            sql = sql.replaceAll(tableName, tableName + " modifyTable ");
                            break;
                        }
                    }
                    //sql = sql.replaceAll(tableName,	"(select * from " + tableName + " where tenant_id = '" + linkappUser.getTenantId() + "') ");

                    //角色配置的空间进行数据隔离。
                    if ("1".equals(linkappUser.getType())) {
                        sql = sql.replaceAll(tableName, "(select * from " + tableName + " where tenant_id = '" + linkappUser.getTenantId() + "') ");
                    } else {
                        for (String roleSpacetableName : roleSpaceinvcationTables()) {
                            if (sql.indexOf(roleSpacetableName) != -1) {
                                List<LinkappSpace> spaceList = linkappUserContextProducer.getCurrentUserSpace(linkappUser.getId());
                                String spacesId = "-1";
                                for (int i = 0; i < spaceList.size(); i++) {
                                    if (i == 0) {
                                        spacesId = "'" + spaceList.get(i).getId() + "'";
                                    } else {
                                        spacesId = spacesId + ",'" + spaceList.get(i).getId() + "'";
                                    }
                                }
                                String roleSpaceSql = "( SELECT modify_a.* FROM " + roleSpacetableName + " modify_a "
                                    + "LEFT JOIN linkapp_area modify_b ON modify_a.area_id = modify_b.id "
                                    + "LEFT JOIN linkapp_area modify_c ON modify_b.area_path = modify_c.area_path or modify_b.area_path like concat(modify_c.area_path,':%') "
                                    + "WHERE modify_a.delete_state = 1 AND modify_a.tenant_id = '" + linkappUser.getTenantId() + "' AND modify_c.id IN (" + spacesId + ") )";
                                if ("linkapp_asset ".equals(roleSpacetableName)) {
                                    roleSpaceSql = "( SELECT modify_a.* FROM " + roleSpacetableName + " modify_a "
                                        + "LEFT JOIN linkapp_area modify_b ON modify_a.asset_area_id = modify_b.id "
                                        + "LEFT JOIN linkapp_area modify_c ON modify_b.area_path = modify_c.area_path or modify_b.area_path like concat(modify_c.area_path,':%') "
                                        + "WHERE modify_a.delete_state = 1 AND modify_a.tenant_id = '" + linkappUser.getTenantId() + "' AND modify_c.id IN (" + spacesId + ") )";
                                }

                                if ("linkapp_alarm_info ".equals(roleSpacetableName)) {
                                    roleSpaceSql = "( SELECT modify_a.* FROM " + roleSpacetableName + " modify_a "
                                        + "LEFT JOIN linkapp_area modify_b ON modify_a.spaceId = modify_b.id "
                                        + "LEFT JOIN linkapp_area modify_c ON modify_b.area_path = modify_c.area_path or modify_b.area_path like concat(modify_c.area_path,':%') "
                                        + "WHERE modify_a.delete_state = 1 AND modify_a.tenant_id = '" + linkappUser.getTenantId() + "' AND modify_c.id IN (" + spacesId + ") )";
                                }

                                if ("linkapp_alarm ".equals(roleSpacetableName)) {
                                    roleSpaceSql = "( SELECT modify_a.* FROM " + roleSpacetableName + " modify_a "
                                        + "LEFT JOIN linkapp_device modify_d ON modify_d.code = modify_a.device_code "
                                        + "LEFT JOIN linkapp_area modify_b ON modify_d.area_id = modify_b.id "
                                        + "LEFT JOIN linkapp_area modify_c ON modify_b.area_path = modify_c.area_path or modify_b.area_path like concat(modify_c.area_path,':%') "
                                        + "WHERE modify_a.tenant_id = '" + linkappUser.getTenantId() + "' AND modify_c.id IN (" + spacesId + ") )";
                                }

                                sql = sql.replaceAll(roleSpacetableName, roleSpaceSql);
                                break;
                            }
                        }
                    }
//					LOGGER.info("after:" + sql);
                }
            }
        }
        // 包装sql后，重置到invocation中
        resetSql2Invocation(invocation, sql);
        // 返回，继续执行
        return invocation.proceed();


    }

    @Override
    public Object plugin(Object obj) {
        return Plugin.wrap(obj, this);
    }

    @Override
    public void setProperties(Properties arg0) {
        // doSomething
    }

    private static List<String> roleSpaceinvcationTables() {
        List<String> list = new ArrayList<>();
        list.add("linkapp_analyze_datasource ");
        list.add("linkapp_device ");
        list.add("linkapp_asset ");
        list.add("linkapp_alarm_info ");
        return list;
    }


    private static List<String> invcationTables() {
        List<String> list = new ArrayList<>();
        list.add("linkapp_space ");
        list.add("linkapp_area ");
        list.add("linkapp_role ");
        list.add("linkapp_analyze_datasource ");
        list.add("linkapp_device ");
        list.add("linkapp_asset ");
        list.add("linkapp_alarm ");
        list.add("smoke_warning ");
        list.add("linkapp_device_model ");
        return list;
    }


    private static List<String> sqlId() {
        List<String> list = new ArrayList<>();
        list.add("selectById");
        list.add("selectBatchIds");
        list.add("selectByMap");
        list.add("selectOne");
        list.add("selectList");
        list.add("selectMaps");
        list.add("selectObjs");
        list.add("selectPage");
        list.add("selectMapsPage");
        list.add("selectCount");
        return list;
    }

    /**
     * 获取sql语句
     */
    private String getSqlByInvocation(Invocation invocation) {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        return boundSql.getSql();
    }

    /**
     * 包装sql后，重置到invocation中
     */
    private void resetSql2Invocation(Invocation invocation, String sql) throws SQLException {
        final Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = statement.getBoundSql(parameterObject);
        MappedStatement newStatement = newMappedStatement(statement, new BoundSqlSqlSource(boundSql));
        MetaObject msObject = MetaObject.forObject(newStatement, new DefaultObjectFactory(),
            new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
        msObject.setValue("sqlSource.boundSql.sql", sql);
        args[0] = newStatement;
    }

    private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource,
            ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());

        return builder.build();
    }

    // 定义一个内部辅助类，作用是包装sq
    class BoundSqlSqlSource implements SqlSource {

        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
}
